package cn.wowjoy.office.pm.view.viewodel;

import android.arch.lifecycle.MediatorLiveData;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.bingoogolapple.androidcommon.adapter.BGABindingRecyclerViewAdapter;
import cn.bingoogolapple.androidcommon.adapter.BGABindingViewHolder;
import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.response.StaffResponse;
import cn.wowjoy.office.databinding.ItemPmReportAllBinding;
import cn.wowjoy.office.databinding.ItemPmReportAllRvBinding;
import cn.wowjoy.office.databinding.ItemPmReportYetRvBinding;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.pm.data.PmReportDetailResponse;
import cn.wowjoy.office.pm.data.PmReportIndexResponse;
import cn.wowjoy.office.pm.data.SubmitResponse;
import cn.wowjoy.office.pm.db.PmListDao;
import cn.wowjoy.office.pm.db.PmListDetailDao;
import cn.wowjoy.office.pm.db.PmReportListDetailEntity;
import cn.wowjoy.office.pm.db.PmReportListEntity;
import cn.wowjoy.office.pm.utils.RUnConfirmAdapter;
import cn.wowjoy.office.utils.PreferenceManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;

public class PmReportViewModel extends NewBaseViewModel {
    private String status;
    public StaffResponse userInfo;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        if (status.equals("80-0")) {
            this.status = "";
            return;
        }
        this.status = status;
    }

    @Inject
    public PmReportViewModel(@NonNull NewMainApplication application) {
        super(application);
        alllinnerAdapter.setItemEventHandler(this);
        yeslinnerAdapter.setItemEventHandler(this);
        nolinnerAdapter.setEventListener(this);
        yetlinnerAdapter.setItemEventHandler(this);
        userInfo = new Gson().fromJson(PreferenceManager.getInstance().getStuffInfo(), StaffResponse.class);

    }

    @Override
    public void onCreateViewModel() {

    }

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        if(status.equals("80-4")) {
            queryYetData(ref,userInfo.getStaffName());
        }else{
            getAllListInfo(ref, "", status);
        }

    }

    @Inject
    ApiService apiService;
    //全部数据
    public MediatorLiveData<LiveDataWrapper<PmReportIndexResponse>> allData = new MediatorLiveData<>();
    //未同步
    public MediatorLiveData<LiveDataWrapper<PmReportIndexResponse>> soonData = new MediatorLiveData<>();
    //未确认
    public MediatorLiveData<LiveDataWrapper<PmReportIndexResponse>> noData = new MediatorLiveData<>();
    //已确认
    public MediatorLiveData<LiveDataWrapper<PmReportIndexResponse>> yesData = new MediatorLiveData<>();

    //全部Task
    public ArrayList<PmReportListEntity> all_list;
    public BGABindingRecyclerViewAdapter<PmReportListEntity, ItemPmReportAllBinding> alllinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_report_all);
    public LRecyclerViewAdapter allAdapter = new LRecyclerViewAdapter(alllinnerAdapter);
    //待完善
    public ArrayList<PmReportListEntity> yet_list;
    public BGABindingRecyclerViewAdapter<PmReportListEntity, ItemPmReportYetRvBinding> yetlinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_report_yet_rv);
    public LRecyclerViewAdapter yetAdapter = new LRecyclerViewAdapter(yetlinnerAdapter);
    //未确认
    public ArrayList<PmReportListEntity> no_list;
    public RUnConfirmAdapter nolinnerAdapter = new RUnConfirmAdapter();
    public LRecyclerViewAdapter noAdapter = new LRecyclerViewAdapter(nolinnerAdapter);
    //已确认
    public ArrayList<PmReportListEntity> yes_list;
    public BGABindingRecyclerViewAdapter<PmReportListEntity, ItemPmReportAllRvBinding> yeslinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_report_all_rv);
    public LRecyclerViewAdapter yesAdapter = new LRecyclerViewAdapter(yeslinnerAdapter);


    public void setYetData(boolean isRefresh,List<PmReportListEntity> data) {
        if (isRefresh) {
            if (null == yet_list)
                yet_list = new ArrayList<>();
            yet_list.clear();
            yet_list.addAll(data);
            yetlinnerAdapter.setData(yet_list);
        } else {
            yetlinnerAdapter.addMoreData(data);
        }
        yetAdapter.removeFooterView();
        if (!isRefresh && (null == data || data.isEmpty())) {
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview, null, false);
            yetAdapter.addFooterView(view);
        }
        yetAdapter.notifyDataSetChanged();
        refreshComplete();
    }
    public MediatorLiveData<LiveDataWrapper< List<PmReportListEntity>>> localSave = new MediatorLiveData<>();
    public void queryYetData(boolean isRefresh,String userName){
        localSave.setValue(LiveDataWrapper.loading(null));
        isRefreshOrLoadMoreLocal(isRefresh);
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<List<PmReportListEntity>>() {
            @Override
            public void subscribe(ObservableEmitter<List<PmReportListEntity>> e) throws Exception {
                List<PmReportListEntity> entities= mPmListDao.getDataByUser(userName,localPageIndex,pageSize);
                Log.e("PXY", "subscribe: "+ entities.toString());
                if(null == entities ){
                    //说明数据库存在这条 要更新
                    entities=new ArrayList<>();
                }
                e.onNext(entities);
            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<List<PmReportListEntity>>() {
                    @Override
                    public void onNext(List<PmReportListEntity> o) {
                        setYetData(isRefresh,o);
                        localSave.setValue(LiveDataWrapper.success(o));
                    }

                    @Override
                    public void onError(Throwable e) {
                        localSave.setValue(LiveDataWrapper.error(e,null));
                    }

                    @Override
                    public void onComplete() {
                    }
                });
        addDisposable(observer);
    }
    public void setPmReportListData(boolean isRefresh, List<PmReportListEntity> data, String pmStatus) {
        switch (pmStatus) {
            case "80-3": //未确认
                if (isRefresh) {
                    if (null == no_list)
                        no_list = new ArrayList<>();
                    no_list.clear();
                    no_list.addAll(data);
                    nolinnerAdapter.setDates(no_list);
                } else {
                    nolinnerAdapter.addMoreDate(data);
                }
                noAdapter.removeFooterView();
                if (!isRefresh && (null == data || data.isEmpty())) {
                    LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                    View view = inflater.inflate(R.layout.nodata_footview, null, false);
                    noAdapter.addFooterView(view);
                }
                noAdapter.notifyDataSetChanged();
                refreshComplete();
                break;
            case "80-1,80-2"://已确认
                if (isRefresh) {
                    if (null == yes_list)
                        yes_list = new ArrayList<>();
                    yes_list.clear();
                    yes_list.addAll(data);
                    yeslinnerAdapter.setData(yes_list);
                } else {
                    yeslinnerAdapter.addMoreData(data);
                }
                yesAdapter.removeFooterView();
                if (!isRefresh && (null == data || data.isEmpty())) {
                    LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                    View view = inflater.inflate(R.layout.nodata_footview, null, false);
                    yesAdapter.addFooterView(view);
                }
                yesAdapter.notifyDataSetChanged();
                refreshComplete();
                break;
            case "80-4"://未同步

            case "":
                if (isRefresh) {
                    if (null == all_list)
                        all_list = new ArrayList<>();
                    all_list.clear();
                    Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<List<PmReportListEntity>>() {
                        @Override
                        public void subscribe(ObservableEmitter<List<PmReportListEntity>> e) throws Exception {
                            List<PmReportListEntity> entities= mPmListDao.getDataByUser(userInfo.getStaffName(),pageIndex,pageSize);
                            if(null == entities ){
                                //说明数据库存在这条 要更新
                                entities=new ArrayList<>();
                            }
                            e.onNext(entities);
                        }
                    }).compose(new RxSchedulerTransformer<>())
                            .subscribeWith(new DisposableObserver<List<PmReportListEntity>>() {
                                @Override
                                public void onNext(List<PmReportListEntity> o) {
                                    all_list.addAll(o);
                                    all_list.addAll(data);
                                    alllinnerAdapter.setData(all_list);
                                    allAdapter.removeFooterView();
                                    allAdapter.notifyDataSetChanged();
                                    refreshComplete();
                                }

                                @Override
                                public void onError(Throwable e) {
                                }

                                @Override
                                public void onComplete() {
                                }
                            });
                    addDisposable(observer);
                } else {
                    alllinnerAdapter.addMoreData(data);
                    allAdapter.removeFooterView();
                    if (!isRefresh && (null == data || data.isEmpty())) {
                        LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                        View view = inflater.inflate(R.layout.nodata_footview, null, false);
                        allAdapter.addFooterView(view);
                    }
                    allAdapter.notifyDataSetChanged();
                    refreshComplete();
                }

        }
    }

    //点击查看详情
    public void onItemClick(BGABindingViewHolder holder, PmReportListEntity model) {
        if(!model.isLocal()){
            getPmReport(model.getId()+"");
        }else{
            onLocalItemClick(holder,model);
        }
    }
//    getApplication().getApplicationContext()
    public void onItemDelete(BGABindingViewHolder holder, PmReportListEntity model) {
        //TODO:删除后台数据
        deleteNotice.setValue(model.getId());
//        deletePmReport(model.getId(), MenuHelper.getAuidS().get("zc_pm"));
    }

    public MediatorLiveData<LiveDataWrapper<PmReportListDetailEntity>> localData = new MediatorLiveData<>();
    public void onLocalItemClick(BGABindingViewHolder holder, PmReportListEntity model) {
        localData.setValue(LiveDataWrapper.loading(null));
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<PmReportListDetailEntity>() {
            @Override
            public void subscribe(ObservableEmitter<PmReportListDetailEntity> e) throws Exception {
                List<PmReportListDetailEntity> pmReportListDetailEntities = mDetailDao.queryExist(model.getQrCode(), model.getUserName());
                e.onNext(pmReportListDetailEntities.get(0));
            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<PmReportListDetailEntity>() {
                    @Override
                    public void onNext(PmReportListDetailEntity o) {
                        localData.setValue(LiveDataWrapper.success(o));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        addDisposable(observer);
    }
    public MediatorLiveData<LiveDataWrapper<Boolean>> dleteLocalData = new MediatorLiveData<>();
    public MediatorLiveData<PmReportListEntity> dleteLocalDataNotice = new MediatorLiveData<>();
    public void onLocalItemDelete(BGABindingViewHolder holder, PmReportListEntity model) {
        dleteLocalDataNotice.setValue(model);
    }
    public void deleteLocal(String qrCode,String userName){
        //TODO:删除本地数据
        dleteLocalData.setValue(LiveDataWrapper.loading(null));
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                mDetailDao.deleteByQRCode(qrCode, userName);
                mPmListDao.deleteByQRCode(qrCode, userName);
                e.onNext(true);
            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean o) {
                        dleteLocalData.setValue(LiveDataWrapper.success(o));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        addDisposable(observer);
    }

    //是否展示底部栏
    public MediatorLiveData<Boolean> bottomShow = new MediatorLiveData<>();
    public void showBottom(boolean isShow) {
        bottomShow.setValue(isShow);
    }
    //显示选择得数量
    public MediatorLiveData<Integer> selectNum = new MediatorLiveData<>();
    public void showSelectNum(Integer num) {
        selectNum.setValue(num);
    }
    //显示选择得数量
    public MediatorLiveData<PmReportListEntity> clickItem = new MediatorLiveData<>();
    public void clickItem(PmReportListEntity response) {
        clickItem.setValue(response);
    }


    //获取所有任务的List
    public void getAllListInfo(boolean isRefresh, String fuzzSearchForPDA, String billStatus) {
        isRefreshOrLoadMore(isRefresh);
        allData.setValue(LiveDataWrapper.loading(null));
        if(billStatus.equals("80-1,80-2")){
            Disposable disposable = apiService.getlistPmReportDataDone(fuzzSearchForPDA, billStatus, pageIndex * pageSize, pageSize, MenuHelper.getAuidS().get("zc_pm"))
                    .flatMap(new ResultDataParse<PmReportIndexResponse>())
                    .compose(new RxSchedulerTransformer<PmReportIndexResponse>())
                    .subscribe(new Consumer<PmReportIndexResponse>() {
                        @Override
                        public void accept(PmReportIndexResponse taskListResponse) throws Exception {
                            setPmReportListData(isRefresh, taskListResponse.getList(), status);
                            allData.setValue(LiveDataWrapper.success(taskListResponse));
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            allData.setValue(LiveDataWrapper.error(throwable, null));
                        }
                    });
            addDisposable(disposable);
        }
//        else if(billStatus.equals("80-3")) {
//            Disposable disposable = apiService.getlistPmReportDataYet(billStatus)
//                    .flatMap(new ResultDataParse<PmReportIndexResponse>())
//                    .compose(new RxSchedulerTransformer<PmReportIndexResponse>())
//                    .subscribe(new Consumer<PmReportIndexResponse>() {
//                        @Override
//                        public void accept(PmReportIndexResponse taskListResponse) throws Exception {
//                            allData.setValue(LiveDataWrapper.success(taskListResponse));
//                            setPmReportListData(isRefresh, taskListResponse.getList(), status);
//                        }
//                    }, new Consumer<Throwable>() {
//                        @Override
//                        public void accept(Throwable throwable) throws Exception {
//                            allData.setValue(LiveDataWrapper.error(throwable, null));
//
//                        }
//                    });
//            addDisposable(disposable);
//        }
        else{
            Disposable disposable = apiService.getlistPmReportData(fuzzSearchForPDA, billStatus, pageIndex * pageSize, pageSize, MenuHelper.getAuidS().get("zc_pm"))
                    .flatMap(new ResultDataParse<PmReportIndexResponse>())
                    .compose(new RxSchedulerTransformer<PmReportIndexResponse>())
                    .subscribe(new Consumer<PmReportIndexResponse>() {
                        @Override
                        public void accept(PmReportIndexResponse taskListResponse) throws Exception {
                            setPmReportListData(isRefresh, taskListResponse.getList(), status);
                            allData.setValue(LiveDataWrapper.success(taskListResponse));
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            allData.setValue(LiveDataWrapper.error(throwable, null));
                        }
                    });
            addDisposable(disposable);
        }


    }

    public MediatorLiveData<LiveDataWrapper<PmReportDetailResponse>> detail = new MediatorLiveData<>();
    //点击查看详情
    public void getPmReport(String id) {
        detail.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getPmReport(id)
                .flatMap(new ResultDataParse<PmReportDetailResponse>())
                .compose(new RxSchedulerTransformer<PmReportDetailResponse>())
                .subscribe(new Consumer<PmReportDetailResponse>() {
                    @Override
                    public void accept(PmReportDetailResponse taskListResponse) throws Exception {
                        detail.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        detail.setValue(LiveDataWrapper.error(throwable, null));
                    }
                });
        addDisposable(disposable);
    }


    //删除远程库的数据
    public MediatorLiveData<LiveDataWrapper<SubmitResponse>> delete = new MediatorLiveData<>();
    public MediatorLiveData<String> deleteNotice = new MediatorLiveData<>();
    public void deletePmReport(String ids, String auid) {
        delete.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.deletePmReport(ids, auid)
                .flatMap(new ResultDataParse<SubmitResponse>())
                .compose(new RxSchedulerTransformer<SubmitResponse>())
                .subscribe(new Consumer<SubmitResponse>() {
                    @Override
                    public void accept(SubmitResponse taskListResponse) throws Exception {
                        nolinnerAdapter.removeDate(ids);
                        delete.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        delete.setValue(LiveDataWrapper.error(throwable, null));
                    }
                });
        addDisposable(disposable);
    }

    public MediatorLiveData<LiveDataWrapper< List<PmReportListDetailEntity>>> scan = new MediatorLiveData<>();
    public void queryByQrCode(String qrCode,String userName){
        scan.setValue(LiveDataWrapper.loading(null));
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<List<PmReportListDetailEntity>>() {
            @Override
            public void subscribe(ObservableEmitter<List<PmReportListDetailEntity>> e) throws Exception {
                List<PmReportListEntity> entities= mPmListDao.searchData(qrCode,userName);
//                if(null == entities ){
//                    //说明数据库存在这条 要更新
//                    entities=new ArrayList<>();
//                }
                if(null != entities){
                    List<PmReportListDetailEntity> exist=  mDetailDao.queryExist(qrCode,userName);
                    e.onNext(exist);
                }else{
                    e.onNext(new ArrayList<PmReportListDetailEntity>());
                }

            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<List<PmReportListDetailEntity>>() {
                    @Override
                    public void onNext(List<PmReportListDetailEntity> o) {
                        scan.setValue(LiveDataWrapper.success(o));
                    }

                    @Override
                    public void onError(Throwable e) {
                        scan.setValue(LiveDataWrapper.error(e,null));
                    }

                    @Override
                    public void onComplete() {
                    }
                });
        addDisposable(observer);
    }
    @Inject
    PmListDetailDao mDetailDao;
    @Inject
    PmListDao mPmListDao;

    private AsyData mAsyData;

    public AsyData getAsyData() {
        if (null == mAsyData)
            mAsyData = new AsyData(mPmListDao, mDetailDao, localData);
        return mAsyData;
    }

    public static class AsyData extends AsyncTask<PmReportListEntity, Void, PmReportListDetailEntity> {
        private PmListDetailDao mDetailDao;
        private PmListDao mPmListDao;
        public MediatorLiveData<LiveDataWrapper<PmReportListDetailEntity>> localData;

        public AsyData(PmListDao mPmListDao, PmListDetailDao detailDao, MediatorLiveData<LiveDataWrapper<PmReportListDetailEntity>> localData) {
            this.mPmListDao = mPmListDao;
            mDetailDao = detailDao;
            this.localData = localData;
        }

        public MediatorLiveData<LiveDataWrapper<PmReportListDetailEntity>> getLocalData() {
            return localData;
        }

        @Override
        protected PmReportListDetailEntity doInBackground(PmReportListEntity... entity) {
            List<PmReportListDetailEntity> pmReportListDetailEntities = mDetailDao.queryExist(entity[0].getQrCode(), entity[0].getUserName());
            return pmReportListDetailEntities.get(0);
        }

        @Override
        protected void onPostExecute(PmReportListDetailEntity aVoid) {
            localData.setValue(LiveDataWrapper.success(aVoid));
        }
    }
}
